<script setup lang="ts">
import {
  NButton,
  NSpace,
  NDataTable,
  NInput,
  type DataTableColumns,
  NPagination,
  NForm,
  NFormItem,
  useDialog,
  NDatePicker,
  useMessage,
  NModal
} from 'naive-ui'
import { h, onDeactivated, onMounted, onUnmounted, reactive, ref } from 'vue'
import TableView from '@/components/TableView.vue'
import EllipseAction from '@/views/common/EllipseAction'
import useFlush from '@/hooks/useFlush'
import { useRouter } from 'vue-router'
import { sendRequest } from '@/utils/api'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'

useFlush('flushIAR', () => queryTableData())
const dialog = useDialog()
const router = useRouter()
const message = useMessage()

const columns: DataTableColumns<any> = [
  {
    title: '鉴定编号',
    key: 'identifyCode'
  },
  {
    title: '鉴定名称',
    key: 'identifyName'
  },
  {
    title: '鉴定日期',
    key: 'identifyTime'
  },
  {
    title: '鉴定地点',
    key: 'identifyAddress'
  },
  {
    title: '鉴定专家',
    key: 'identifyExperts',
    render: (e) => e.identifyExperts?.join('，')
  },
  {
    title: '描述',
    key: 'identifyDescription'
  },
  {
    title: '操作',
    align: 'center',
    key: 'action',
    width: 200,
    fixed: 'right',
    render: (e: any) => {
      return h(EllipseAction, {
        actions: () => [
          h(
            NButton,
            {
              color: '#6CB187',
              quaternary: true,
              size: 'small',
              onClick: () => {
                router.push({
                  name: 'identifyDetail',
                  params: {
                    id: e.batchId
                  },
                  query: {
                    identifyId: e.id,
                    redirect: router.currentRoute.value.fullPath
                  }
                })
              }
            },
            { default: () => '详情' }
          ),
          h(
            NButton,
            {
              color: '#6CB187',
              quaternary: true,
              size: 'small',
              onClick: () => {
                router.push({
                  name: 'registerTFEdit',
                  params: {
                    id: e.id
                  },
                  query: {
                    batchId: e.batchId,
                    from: 'record',
                    redirect: router.currentRoute.value.fullPath
                  }
                })
              }
            },
            { default: () => '编辑' }
          )
          // h(
          //   NButton,
          //   {
          //     color: '#FC355D',
          //     quaternary: true,
          //     size: 'small',
          //     onClick: () => handleDelete(e.id)
          //   },
          //   { default: () => '删除' }
          // )
          //   h(
          //     NButton,
          //     {
          //       color: '#6CB187',
          //       quaternary: true,
          //       size: 'small',
          //       onClick: () => {
          //         router.push({
          //           name: 'registerTF',
          //           params: {
          //             id: e.batchId
          //           },
          //           query: {
          //             from: 'record',
          //             redirect: router.currentRoute.value.fullPath
          //           }
          //         })
          //       }
          //     },
          //     { default: () => '鉴定登记' }
          //   ),
          //   h(
          //     NButton,
          //     {
          //       color: '#6CB187',
          //       quaternary: true,
          //       size: 'small',
          //       onClick: () => handleEndIdentity(e.batchId)
          //     },
          //     { default: () => '结束鉴定' }
          //   )
        ]
      })
    }
  }
]
// 查询字段
const form = reactive({
  identifyName: null,
  startDate: null,
  endDate: null
})
// 获取列表数据
const tableData = ref<any>([])
const tableLoading = ref(false)
const resetForm = () => {
  form.identifyName = null
  form.startDate = null
  form.endDate = null
}
const queryTableData = async () => {
  try {
    tableLoading.value = true
    const [error, res] = await sendRequest({
      module: 'identify',
      api: 'identifyListVo',
      override: {
        params: {
          limit: paginationReactive.pageSize,
          page: paginationReactive.page,
          ...form
        }
      }
    })
    if (error) return message.error(error.message)
    tableData.value = res.data.list
    paginationReactive.itemCount = res.data.totalCount
  } catch (error) {
    console.log(error)
  } finally {
    tableLoading.value = false
  }
}
// 上一页下一页
const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 0,
  onChange: (page: number) => {
    paginationReactive.page = page
    queryTableData()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
    queryTableData()
  }
})
// 时间选择
const handleDateTime = (v: any) => {
  if (v) {
    form.startDate = v[0]
    form.endDate = v[1]
  } else {
    form.startDate = null
    form.endDate = null
  }
}
// 结束鉴定
// const handleEndIdentity = (id: any) => {
//   dialog.warning({
//     title: '是否对当前物品结束鉴定？',
//     positiveText: '确认',
//     negativeText: '取消',
//     onPositiveClick: async () => {
//       try {
//         tableLoading.value = true
//         const [error, res] = await sendRequest({
//           module: 'identify',
//           api: 'finishIdentify',
//           override: {
//             params: {
//               batchId: id
//             }
//           }
//         })
//         if (error) return message.error(error.message)
//         if (res.code !== 0) return message.error(res.msg)
//         message.success('结束鉴定成功')
//         queryTableData()
//       } catch (error) {
//         console.log(error)
//       } finally {
//         tableLoading.value = false
//       }
//     }
//   })
// }
// 删除
const modalVisible = ref(false)
const deleteId = ref<number | null>(null)
const handleDeleteConfirm = async () => {
  try {
    const [error, res] = await sendRequest({
      module: 'identify',
      api: 'identifyDelete',
      override: {
        data: [deleteId.value]
      }
    })
    if (error) return message.error(error.message)
    if (res.code !== 0) return message.error(res.msg)
    message.success('删除成功')
    queryTableData()
    modalVisible.value = false
    deleteId.value = null
  } catch (error) {
    console.log(error)
  } finally {
    modalVisible.value = false
    deleteId.value = null
  }
}
// const handleDelete = (id: any) => {
//   modalVisible.value = true
//   deleteId.value = id
// }

onMounted(() => queryTableData())
onUnmounted(() => dialog.destroyAll())
onDeactivated(() => dialog.destroyAll())
</script>

<template>
  <TableView class="iar">
    <template #form>
      <NSpace
        justify="space-between"
        @keydown.enter=";(paginationReactive.page = 1), queryTableData()"
      >
        <NSpace align="center">
          <NForm
            label-placement="left"
            :show-feedback="false"
            inline
          >
            <NFormItem label="鉴定名称：">
              <NInput
                placeholder="请输入鉴定名称"
                clearable
                v-model:value="form.identifyName"
              />
            </NFormItem>
            <NFormItem label="日期：">
              <NDatePicker
                input-readonly
                type="daterange"
                placeholder="请选择日期"
                clearable
                :formatted-value="
                  form.startDate && form.endDate ? [form.startDate, form.endDate] : null
                "
                @update:formatted-value="handleDateTime"
              />
            </NFormItem>
          </NForm>
          <NButton
            :disabled="tableLoading"
            :loading="tableLoading"
            color="#6CB187"
            style="min-width: 78rem; margin-right: 0rem"
            ghost
            @click=";(paginationReactive.page = 1), queryTableData()"
          >
            查询
          </NButton>
          <NButton
            :disabled="tableLoading"
            color="#6CB187"
            style="min-width: 78rem"
            @click="resetForm"
            ghost
          >
            重置
          </NButton>
        </NSpace>
        <!-- 
        <NButton
          :disabled="tableLoading"
          :loading="tableLoading"
          color="#6CB187"
          style="min-width: 115rem"
          @click="$router.push({ name: 'identifyApply', query: { redirect: $route.fullPath } })"
        >
          +鉴定申请
        </NButton> -->
      </NSpace>
    </template>
    <template #table="props">
      <n-data-table
        v-bind="props"
        :data="tableData"
        :columns="columns"
        :loading="tableLoading"
        bordered
      />
    </template>
    <template #pagination>
      <NPagination
        show-size-picker
        show-quick-jumper
        :page-sizes="paginationReactive.pageSizes"
        :item-count="paginationReactive.itemCount"
        :page="paginationReactive.page"
        :page-size="paginationReactive.pageSize"
        @update:page="paginationReactive.onChange"
        @update:page-size="paginationReactive.onUpdatePageSize"
      >
        <template #suffix>页</template>
        <template #prefix>
          <span style="font-size: 14px">共{{ paginationReactive.itemCount }}条</span>
        </template>
      </NPagination>
    </template>
  </TableView>

  <NModal
    :auto-focus="false"
    v-model:show="modalVisible"
  >
    <VDialogContent
      @close="modalVisible = false"
      @submit="handleDeleteConfirm"
      title="删除提示"
    >
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        是否删除当前鉴定记录?
      </div>
    </VDialogContent>
  </NModal>
</template>

<style scoped lang="scss">
.iar {
  padding: 29rem 30rem;
  gap: 25rem 0;
}
</style>
